package com.jilian.mydemo.modul.exam.ui;

import android.Manifest;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.jilian.mydemo.MyApplication;
import com.jilian.mydemo.R;
import com.jilian.mydemo.base.BaseActivity;
import com.jilian.mydemo.base.BaseDto;
import com.jilian.mydemo.city.Interface.OnCityItemClickListener;
import com.jilian.mydemo.city.bean.CityBean;
import com.jilian.mydemo.city.bean.DistrictBean;
import com.jilian.mydemo.city.bean.ProvinceBean;
import com.jilian.mydemo.city.style.citypickerview.CityPickerView;
import com.jilian.mydemo.common.vo.ServiceAreaVo;
import com.jilian.mydemo.dialog.nicedialog.BaseNiceDialog;
import com.jilian.mydemo.dialog.nicedialog.NiceDialog;
import com.jilian.mydemo.dialog.nicedialog.ViewConvertListener;
import com.jilian.mydemo.dialog.nicedialog.ViewHolder;
import com.jilian.mydemo.modul.user.activity.IsReviewingActivity;
import com.jilian.mydemo.modul.user.viewmodel.UserViewModel;
import com.jilian.mydemo.utils.EmptyUtils;
import com.jilian.mydemo.utils.PermissionsObserver;
import com.jilian.mydemo.utils.ToastUitl;
import com.jilian.mydemo.utils.Utils;
import com.jilian.mydemo.utils.selectphoto.SelectPhotoUtils;

import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static com.jilian.mydemo.Constant.FINALVALUE.FILE_PROVIDER;

public class PartnershipApplicationActivity extends BaseActivity {
    private TextView tvArea;
    private ImageView ivOne;
    private ImageView ivTwo;
    private TextView tvOk;
    private RelativeLayout rlOne;
    private RelativeLayout rlTwo;
    private int photoType;//1 左 2 右
    private ImageView ivCloseOne;
    private ImageView ivCloseTwo;
    private String province = "";//省
    private String city = "";//市
    private String area = "";//区
    private EditText tvName;
    private EditText tvPhone;
    private EditText tvAge;
    private EditText tvOlds;
    private EditText tvSize;
    private EditText tvAdress;
    private UserViewModel viewModel;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyApplication.addActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication.removeActivity(this);
    }


    @Override
    protected void createViewModel() {
        viewModel = ViewModelProviders.of(this).get(UserViewModel.class);
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_partnershipapplication;
    }

    @Override
    public void initView() {
        setNormalTitle("合伙人申请", v -> finish());
        tvArea = (TextView) findViewById(R.id.tv_area);
        ivOne = (ImageView) findViewById(R.id.iv_one);
        ivTwo = (ImageView) findViewById(R.id.iv_two);
        tvOk = (TextView) findViewById(R.id.tv_ok);
        rlOne = (RelativeLayout) findViewById(R.id.rl_one);
        rlTwo = (RelativeLayout) findViewById(R.id.rl_two);

        ivCloseOne = (ImageView) findViewById(R.id.iv_close_one);
        ivCloseTwo = (ImageView) findViewById(R.id.iv_close_two);

        tvName = (EditText) findViewById(R.id.tv_name);
        tvPhone = (EditText) findViewById(R.id.tv_phone);
        tvAge = (EditText) findViewById(R.id.tv_age);
        tvOlds = (EditText) findViewById(R.id.tv_olds);
        tvSize = (EditText) findViewById(R.id.tv_size);
        tvAdress = (EditText) findViewById(R.id.tv_adress);
        rlOne = (RelativeLayout) findViewById(R.id.rl_one);
        ivOne = (ImageView) findViewById(R.id.iv_one);
        ivCloseOne = (ImageView) findViewById(R.id.iv_close_one);
        rlTwo = (RelativeLayout) findViewById(R.id.rl_two);
        ivTwo = (ImageView) findViewById(R.id.iv_two);
        ivCloseTwo = (ImageView) findViewById(R.id.iv_close_two);
        tvOk = (TextView) findViewById(R.id.tv_ok);

    }

    @Override
    public void initData() {

    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1001:
                    getLoadingDialog().dismiss();
                    CityPickerView pickerView = (CityPickerView) msg.obj;
                    pickerView.showCityPicker();
                    //监听选择点击事件及返回结果
                    pickerView.setOnCityItemClickListener(new OnCityItemClickListener() {
                        @Override
                        public void onSelected(ProvinceBean province, CityBean city, DistrictBean district) {

                            //省份
                            if (province != null) {
                                PartnershipApplicationActivity.this.province = province.getPROVINCE();
                            }

                            //城市
                            if (city != null) {
                                PartnershipApplicationActivity.this.city = city.getCITY();
                            }

                            //地区
                            if (district != null) {
                                PartnershipApplicationActivity.this.area = district.getAREA();
                            }
                            tvArea.setText(province.getPROVINCE() + city.getCITY() + district.getAREA());
                            updateEnableStatus();
                        }

                        @Override
                        public void onCancel() {
                            ToastUitl.showImageToastTips("已取消");
                        }
                    });
                    break;
            }
        }
    };

    @Override
    public void initListener() {
        tvSize.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (Utils.doubleyn(tvSize.getText().toString(),3)) {
                    tvSize.setText(  tvSize.getText().toString().substring(0,tvSize.getText().toString().length()-1));
                    tvSize.setSelection(tvSize.getText().toString().length());//将光标移至文字末尾
                }
            }
        });
        tvArea.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getLoadingDialog().showDialog();
                new Thread() {
                    @Override
                    public void run() {
                        CityPickerView pickerView = getPickerInstance("选择服务区域",2);

                        Message message = Message.obtain();
                        message.obj = pickerView;
                        message.what = 1001;
                        handler.sendMessage(message);
                    }
                }.start();
            }
        });
        rlOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                photoType = 1;
                showSelectPhotoTypeDialog();

            }
        });
        rlTwo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                photoType = 2;
                showSelectPhotoTypeDialog();
            }
        });
        ivCloseOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onePath = null;
                ivOne.setImageResource(R.drawable.image_add_photo);
                ivCloseOne.setVisibility(View.GONE);
                storeLogo.clear();
                updateEnableStatus();
            }
        });
        ivCloseTwo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                twoPath = null;
                ivTwo.setImageResource(R.drawable.image_add_photo);
                ivCloseTwo.setVisibility(View.GONE);
                businessLicense.clear();
                updateEnableStatus();
            }
        });
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!Utils.checkPhoneNo(tvPhone.getText().toString())){
                    ToastUitl.showImageToastTips(getResources().getString(R.string.error_phone));
                    return;
                }
                showLoadingDialog();
                ServiceAreaVo vo = new ServiceAreaVo();
                vo.setProvince(province);
                vo.setCity(city);
                vo.setDistrict(area);
                viewModel.partnerApply(
                        tvAge.getText().toString(),
                        tvName.getText().toString(),
                        tvPhone.getText().toString(),
                        tvAdress.getText().toString(),
                        tvSize.getText().toString(),
                        tvOlds.getText().toString(),
                        JSONObject.toJSONString(vo),
                        businessLicense,
                        storeLogo);
                viewModel.getPartnerApplyliveData().observe(PartnershipApplicationActivity.this, new Observer<BaseDto>() {
                    @Override
                    public void onChanged(@Nullable BaseDto dto) {
                        hideLoadingDialog();
                        if (dto.isSuccess()) {
                            Intent intent = new Intent(PartnershipApplicationActivity.this, IsReviewingActivity.class);
                            intent.putExtra("title", "合伙人申请");
                            startActivity(intent);
                            finish();
                        } else {
                            ToastUitl.showImageToastTips(dto.getMsg());
                        }
                    }
                });


            }
        });
    }

    //相机
    private final int FROM_CAPTURE = 10001;
    //相册
    private final int FROM_ALBUM = 10002;

    /**
     * 选中照片
     */
    private void showSelectPhotoTypeDialog() {
        NiceDialog.init()
                .setLayoutId(R.layout.dialog_photo_select)
                .setConvertListener(new ViewConvertListener() {
                    @Override
                    public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                        dialog.setOutCancel(false);
                        Button btnTakingPictures = (Button) holder.getView(R.id.btn_taking_pictures);
                        Button btnPhotoAlbum = (Button) holder.getView(R.id.btn_photo_album);
                        Button btnCancel = (Button) holder.getView(R.id.btn_cancel);
                        btnCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dialog.dismiss();
                            }
                        });
                        //拍照
                        btnTakingPictures.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dialog.dismiss();
                                RxPermissions.getInstance(PartnershipApplicationActivity.this).request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new PermissionsObserver() {
                                    @Override
                                    protected void onGetPermissionsSuccess() {
                                        SelectPhotoUtils.fromCapture(PartnershipApplicationActivity.this, FILE_PROVIDER, FROM_CAPTURE);
                                    }

                                    @Override
                                    protected void onGetPermissionsSuccessFailuer() {
                                        ToastUitl.showImageToastTips("相机权限被拒绝，无法使用拍照功能");
                                    }
                                });

                            }
                        });
                        //相册
                        btnPhotoAlbum.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dialog.dismiss();

                                RxPermissions.getInstance(PartnershipApplicationActivity.this).request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new PermissionsObserver() {
                                    @Override
                                    protected void onGetPermissionsSuccess() {
                                        SelectPhotoUtils.fromAlbum(PartnershipApplicationActivity.this, FILE_PROVIDER, 1, FROM_ALBUM);
                                    }

                                    @Override
                                    protected void onGetPermissionsSuccessFailuer() {
                                        ToastUitl.showImageToastTips("相机权限被拒绝，无法使用拍照功能");
                                    }
                                });

                            }

                        });

                    }
                })
                .setShowBottom(true)
                .show(getSupportFragmentManager());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                //图库
                case FROM_ALBUM:
                    List<Uri> uriList = SelectPhotoUtils.albumResult(data);
                    Uri uri = uriList.get(0);
                    initPath(SelectPhotoUtils.getRealPathFromURI(this, uri));
                    break;
                //相机
                case FROM_CAPTURE:
                    initPath(SelectPhotoUtils.capturePathResult());
                    break;
            }

        }
    }

    private String onePath;//左边图片的地址

    private String twoPath;//右边图片的地址
    private List<File> businessLicense;
    private List<File> storeLogo;

    /**
     * 设置图片地址
     *
     * @param url
     */
    private void initPath(String url) {
        if (photoType == 1) {
            onePath = url;
            Glide
                    .with(this)
                    .load(url)
                    .into(ivOne);
            ivCloseOne.setVisibility(View.VISIBLE);
            storeLogo = new ArrayList<>();
            storeLogo.add(new File(url));
        }
        if (photoType == 2) {
            twoPath = url;
            Glide
                    .with(this)
                    .load(url)
                    .into(ivTwo);
            ivCloseTwo.setVisibility(View.VISIBLE);
            businessLicense = new ArrayList<>();
            businessLicense.add(new File(url));
        }
        updateEnableStatus();
    }

    /**
     * 更新按钮的状态
     */
    private void updateEnableStatus() {
        if (
                !TextUtils.isEmpty(tvName.getText().toString())
                && !TextUtils.isEmpty(tvPhone.getText().toString())
                && !TextUtils.isEmpty(tvArea.getText().toString())
                && !TextUtils.isEmpty(tvAge.getText().toString())
                && !TextUtils.isEmpty(tvOlds.getText().toString())
                && !TextUtils.isEmpty(tvSize.getText().toString())
                && !TextUtils.isEmpty(tvAdress.getText().toString())
                && !TextUtils.isEmpty(tvArea.getText().toString())
                && EmptyUtils.isNotEmpty(businessLicense)
                && EmptyUtils.isNotEmpty(storeLogo)
                )

        {
            tvOk.setEnabled(true);
            tvOk.setBackgroundResource(R.drawable.shape_btn_login_normal);
        } else {
            tvOk.setEnabled(false);
            tvOk.setBackgroundResource(R.drawable.shape_btn_login_dark);
        }
    }
}
